import threading
import subprocess
import signal
import sys
import time

try:
    import ser_read
except Exception as e:
    print(e)


def signal_handler(sig, frame):
    global running
    running = False


def test_2(host, file_name,timeout=5, interval=0.3):
    global running
    running = True

    # 注册信号处理程序以捕获键盘中断
    signal.signal(signal.SIGINT, signal_handler)

    total_packets = 0
    received_packets = 0
    total_time = 0.0
    min = 99999
    max = 0
    avg = 0
    try:
        th1 = threading.Thread(target=ser_read.ser_read_demo2, )
        th1.start()
    except Exception as e:
        print(e)

    try:
        # cmd = ['ping', host]
        cmd = ['ping', '-i', str(interval), host]
        process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

        while running:
            output = process.stdout.readline().decode('utf-8')
            if not output:
                break

            if 'time=' in output:
                total_packets += 1
                received_packets += 1

                file = open(f'{file_name}_net.csv', 'a+', encoding='utf-8')
                out = f'{time.time()} : {output.strip()}'
                print(out)
                file.write(out + '\n')
                time.sleep(0.1)
                time_pos = output.find('time=')
                time_str = output[time_pos:].split()[0][5:]
                time_str = float(time_str)
                if time_str > max:
                    max = time_str
                if time_str < min:
                    min = time_str
                total_time += time_str

            elif 'Destination Host Unreachable' in output or 'Request timeout' in output:
                total_packets += 1

                print(output.strip())

    except Exception as e:
        print(f'Error: {e}')

    finally:
        process.terminate()

    if total_packets > 0:
        packet_loss = ((total_packets - received_packets) / total_packets) * 100
        avg_time = total_time / received_packets if received_packets > 0 else 0
        print(f'\n--- {host} ping statistics ---')
        print(f'{total_packets} packets transmitted, {received_packets} received, {packet_loss:.2f}% packet loss')
        print(f'rtt min/avg/max = {min}/{avg_time:.3f}/{max} ms')


# host = '127.0.0.1'
host = '192.168.31.122'
# test_2(host, file_name = time.time(),interval=0.3)


def ping_plot(filepath):
    import numpy as np

    import pyqtgraph as pg

    win = pg.GraphicsLayoutWidget(show=True)
    win.setBackground('white')

    m = win.addPlot()
    ping_line = ''
    x = []
    y = []
    start_time = 0
    with open(filepath, 'r', encoding='utf-8') as f:
        data = f.read()
        for line in data.split('\n'):
            if 'time=' in line:
                if start_time == 0:
                    start_time = float(line.split(' ')[0])

                x.append(float(line.split(' ')[0]) - start_time)
                y.append(float(line[line.find('time='):].split()[0][5:]))
                # print(line)
    print(x)
    m.plot(x=x, y=y, symbolPen='w', title="yuan de test plot")
    m.setLabel('left', 'Ping Time (ms)')  # 设置 Y 轴标签
    m.setLabel('bottom', 'Time (s)')  # 设置 X 轴标签
    pg.exec()

ping_plot('data1.csv')
